import Vue from 'vue';
import oeLoading from '@/components/loading/index.vue';
const oe = Vue.extend(oeLoading);
const loadingDirective = {};
loadingDirective.install = (Vue) => {
  const toggleLoging = (el, binding) => {
    if (binding.value) {
      insertDom(document.body, el, binding);
    } else {
      el.instance.visible = false;
    }
  };
  // 删除已经存在的loading
  const delelteDom = () => {
    let loading = document.querySelectorAll('.oe-loading');
    let arrLoading = Array.prototype.slice.call(loading);
    if (arrLoading.length) {
      arrLoading.forEach((dom) => {
        let loadingParentNode = dom.parentNode;
        loadingParentNode.removeChild(dom);
      });
    }
  };
  const insertDom = (dom, el, binding) => {
    el.instance.visible = true;
    dom.appendChild(el.load);
  };

  Vue.directive('loading', {
    bind: (el, binding, vnode) => {
      delelteDom();
      // 获取文本设置属性
      var textExr = el.getAttribute('loading-text');
      var iconExr = el.getAttribute('loading-icon');
      var backgroundExr = el.getAttribute('loading-bg');
      var text = textExr ? textExr : '加载中...';
      var bgColor = backgroundExr ? backgroundExr : 'rgba(255,255,255,0.3)';
      var icon = iconExr ? iconExr : '';
      const load = new oe({
        el: document.createElement('div')
      });
      // 将dom注册在el下
      el.instance = load;
      // 给loading.vue的值设置值
      el.instance.text = text;
      el.instance.color = bgColor;
      el.instance.icon = icon;
      // 挂载组件
      el.load = load.$el;
      binding.value && toggleLoging(el, binding);
    },
    update: (el, binding) => {
      if (binding.oldValue !== binding.value) {
        toggleLoging(el, binding);
      }
    },
    unbind: function(el, binding) {
      el.instance && el.instance.$destroy();
    }
  });
};
export default loadingDirective;
